<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  QuestionFilled,
  Plus,
  Edit,
  Delete,
  Search,
  Document,
  Top,
  View
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// 当前活跃标签
const activeTab = ref<'notice' | 'faq'>('notice')

// 列表数据
const noticeList = ref<any[]>([])
const faqList = ref<any[]>([])

// 分页信息
const noticePagination = reactive({
  page: 1,
  limit: 10, // 移动端减少每页数量
  total: 0
})

const faqPagination = reactive({
  page: 1,
  limit: 10,
  total: 0
})

// 搜索关键词
const searchQuery = ref('')

// 加载状态
const loading = ref(false)

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEditing = ref(false)
const currentId = ref<string | null>(null)

const form = reactive({
  title: '',
  content: '',
  isPinned: false,
  isPublished: false
})

// 当前列表及分页计算
const currentList = computed(() => activeTab.value === 'notice' ? noticeList.value : faqList.value)
const currentPagination = computed(() => activeTab.value === 'notice' ? noticePagination : faqPagination)

// API基础路径
const getApiPath = (type: 'notice' | 'faq') => {
  return type === 'notice' ? '/api/admin/notices' : '/api/admin/faqs'
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const apiPath = getApiPath(activeTab.value)
    const params = {
      page: currentPagination.value.page,
      limit: currentPagination.value.limit,
      ...(searchQuery.value && { q: searchQuery.value })
    }

    const response = await request.get(apiPath, { params })
    const { items, total } = response.data

    if (activeTab.value === 'notice') {
      noticeList.value = items
      noticePagination.total = total
    } else {
      faqList.value = items
      faqPagination.total = total
    }
  } catch (error) {
    console.error('목록 가져오기 실패:', error)
    ElMessage.error('목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

// 标签切换
const handleTabChange = (tab: string) => {
  activeTab.value = tab as 'notice' | 'faq'
  searchQuery.value = ''
  fetchList()
}

// 搜索
const handleSearch = () => {
  currentPagination.value.page = 1
  fetchList()
}

// 页面变更
const handlePageChange = (page: number) => {
  currentPagination.value.page = page
  fetchList()
}

// 表单重置
const resetForm = () => {
  form.title = ''
  form.content = ''
  form.isPinned = false
  form.isPublished = false
  currentId.value = null
  isEditing.value = false
}

// 添加
const handleAdd = () => {
  resetForm()
  dialogTitle.value = `${activeTab.value === 'notice' ? '공지사항' : 'FAQ'} 추가`
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (item: any) => {
  try {
    const apiPath = getApiPath(activeTab.value)
    const response = await request.get(`${apiPath}/${item.id}`)
    const data = response.data

    form.title = data.title
    form.content = data.content
    form.isPinned = data.isPinned
    form.isPublished = data.isPublished
    currentId.value = item.id
    isEditing.value = true
    dialogTitle.value = `${activeTab.value === 'notice' ? '공지사항' : 'FAQ'} 수정`
    dialogVisible.value = true
  } catch (error) {
    console.error('데이터 로드 실패:', error)
    ElMessage.error('데이터 로드 실패')
  }
}

// 删除
const handleDelete = async (item: any) => {
  try {
    await ElMessageBox.confirm(
      `"${item.title}"을(를) 삭제하시겠습니까?`,
      '확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning',
      }
    )

    const apiPath = getApiPath(activeTab.value)
    await request.delete(`${apiPath}/${item.id}`)
    ElMessage.success('삭제 성공')
    fetchList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('삭제 실패:', error)
      ElMessage.error('삭제 실패')
    }
  }
}

// 保存
const handleSave = async () => {
  if (!form.title.trim() || !form.content.trim()) {
    ElMessage.error('제목과 내용은 비워둘 수 없습니다')
    return
  }

  try {
    const apiPath = getApiPath(activeTab.value)
    const data = {
      title: form.title.trim(),
      content: form.content.trim(),
      isPinned: form.isPinned,
      isPublished: form.isPublished
    }

    if (isEditing.value && currentId.value) {
      await request.put(`${apiPath}/${currentId.value}`, data)
      ElMessage.success('업데이트 성공')
    } else {
      await request.post(apiPath, data)
      ElMessage.success('생성 성공')
    }

    dialogVisible.value = false
    fetchList()
  } catch (error) {
    console.error('저장 실패:', error)
    ElMessage.error('저장 실패')
  }
}

// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleDateString('ko-KR')
}

// 页面加载时获取数据
onMounted(() => {
  fetchList()
})
</script>

<template>
  <div class="notice-faq-view">
    <!-- 页面标题 -->
    <div class="page-header mobile-padding">
      <div class="header-content">
        <el-icon class="page-icon" size="24">
          <Bell v-if="activeTab === 'notice'" />
          <QuestionFilled v-else />
        </el-icon>
        <div class="header-text">
          <h1 class="page-title">공지사항 및 FAQ 관리</h1>
          <p class="page-subtitle">시스템 공지사항과 자주 묻는 질문을 관리합니다</p>
        </div>
      </div>
    </div>

    <div class="page-content">
      <!-- 标签切换 -->
      <div class="tabs-section mobile-padding">
        <div class="mobile-tabs">
          <div
            class="mobile-tab-item"
            :class="{ active: activeTab === 'notice' }"
            @click="handleTabChange('notice')"
          >
            <el-icon><Bell /></el-icon>
            <span>공지사항</span>
          </div>
          <div
            class="mobile-tab-item"
            :class="{ active: activeTab === 'faq' }"
            @click="handleTabChange('faq')"
          >
            <el-icon><QuestionFilled /></el-icon>
            <span>FAQ</span>
          </div>
        </div>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar-section mobile-padding">
        <div class="mobile-toolbar">
          <el-button
            type="primary"
            size="default"
            @click="handleAdd"
            style="flex: 1;"
          >
            <el-icon><Plus /></el-icon>
            {{ activeTab === 'notice' ? '공지사항' : 'FAQ' }} 추가
          </el-button>
        </div>

        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchQuery"
            placeholder="제목 검색..."
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </div>
      </div>

      <!-- 列表 -->
      <div class="list-section mobile-padding">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <div v-else-if="currentList.length === 0" class="empty-state">
          <el-empty
            :description="`${activeTab === 'notice' ? '공지사항이' : 'FAQ가'} 없습니다`"
            :image-size="120"
          />
        </div>

        <div v-else class="mobile-list">
          <div
            v-for="item in currentList"
            :key="item.id"
            class="mobile-list-item"
          >
            <div class="item-content">
              <div class="item-header">
                <div class="item-title">
                  <el-icon v-if="item.isPinned" class="pin-icon">
                    <Top />
                  </el-icon>
                  {{ item.title }}
                </div>
                <div class="item-badges">
                  <el-tag
                    v-if="item.isPinned"
                    type="warning"
                    size="small"
                  >
                    고정
                  </el-tag>
                  <el-tag
                    :type="item.isPublished ? 'success' : 'info'"
                    size="small"
                  >
                    {{ item.isPublished ? '발행됨' : '초안' }}
                  </el-tag>
                </div>
              </div>

              <div class="item-meta">
                <span class="item-date">{{ formatDate(item.createdAt) }}</span>
              </div>
            </div>

            <div class="item-actions">
              <el-button
                type="primary"
                size="small"
                text
                @click="handleEdit(item)"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="danger"
                size="small"
                text
                @click="handleDelete(item)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="currentPagination.total > currentPagination.limit" class="pagination-section">
          <el-pagination
            v-model:current-page="currentPagination.page"
            :page-size="currentPagination.limit"
            :total="currentPagination.total"
            layout="prev, pager, next"
            @current-change="handlePageChange"
            small
          />
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="95%"
      :close-on-click-modal="false"
      class="mobile-dialog"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="제목" required>
          <el-input
            v-model="form.title"
            placeholder="제목을 입력하세요"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="내용" required>
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="내용을 입력하세요"
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="옵션">
          <div class="form-options">
            <el-checkbox v-model="form.isPinned">
              <el-icon><Top /></el-icon>
              고정
            </el-checkbox>
            <el-checkbox v-model="form.isPublished">
              <el-icon><View /></el-icon>
              발행
            </el-checkbox>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" style="flex: 1;">
            취소
          </el-button>
          <el-button type="primary" @click="handleSave" style="flex: 1;">
            저장
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.notice-faq-view {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

/* 页面标题 */
.page-header {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: var(--mobile-content-padding);
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-icon {
  color: var(--el-color-primary);
}

.header-text {
  flex: 1;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--el-text-color-regular);
  margin: 0;
}

/* 标签切换 */
.tabs-section {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.mobile-tabs {
  display: flex;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;
  padding: 4px;
}

.mobile-tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 12px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  color: var(--el-text-color-regular);
  cursor: pointer;
  transition: all 0.2s ease;
}

.mobile-tab-item.active {
  background: var(--el-color-primary);
  color: white;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

.mobile-tab-item:not(.active):hover {
  color: var(--el-color-primary);
}

/* 工具栏 */
.toolbar-section {
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-lighter);
  padding: var(--mobile-content-padding);
}

.mobile-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.search-box {
  width: 100%;
}

/* 列表 */
.list-section {
  flex: 1;
}

.loading-container {
  padding: 20px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.mobile-list {
  background: var(--el-bg-color);
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 16px;
}

.mobile-list-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  transition: background-color 0.2s ease;
}

.mobile-list-item:last-child {
  border-bottom: none;
}

.mobile-list-item:active {
  background: var(--el-fill-color-light);
}

.item-content {
  flex: 1;
  min-width: 0;
}

.item-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 8px;
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  line-height: 1.4;
  display: flex;
  align-items: center;
  gap: 6px;
  flex: 1;
  min-width: 0;
  word-break: break-word;
}

.pin-icon {
  color: var(--el-color-warning);
  flex-shrink: 0;
}

.item-badges {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
}

.item-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-date {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.item-actions {
  display: flex;
  gap: 8px;
  margin-left: 12px;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 对话框 */
.mobile-dialog {
  --el-dialog-margin-top: 5vh;
}

.mobile-dialog .el-dialog {
  margin: 5vh auto;
  border-radius: 16px;
}

.mobile-dialog .el-dialog__header {
  padding: 20px 20px 10px;
}

.mobile-dialog .el-dialog__body {
  padding: 10px 20px 20px;
}

.mobile-dialog .el-dialog__footer {
  padding: 0 20px 20px;
}

.form-options {
  display: flex;
  gap: 20px;
}

.form-options .el-checkbox {
  display: flex;
  align-items: center;
  gap: 6px;
}

.dialog-footer {
  display: flex;
  gap: 12px;
}

/* 响应式适配 */
@media (max-width: 480px) {
  .page-title {
    font-size: 18px;
  }

  .page-subtitle {
    font-size: 13px;
  }

  .mobile-tab-item {
    padding: 10px 12px;
    font-size: 13px;
  }

  .item-title {
    font-size: 15px;
  }

  .item-badges {
    flex-direction: column;
    gap: 4px;
  }

  .form-options {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
